package com.qiaofang.collectmanagebff.facade.globalexception.handler;


import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.collectmanagebff.base.constants.CollectManageBffResponseCode;


/**
 * 全局异常处理器
 * @author Administrator
 *
 */
@RestController
@ControllerAdvice
public class CollectManageBffGlobalExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(CollectManageBffGlobalExceptionHandler.class);

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        CommonResponse response = new CommonResponse();
		LOGGER.error("There is exception happening",e);
		if(e instanceof BusinessException){
			response.setResponseCode(((BusinessException) e).getErrorCode());
			response.setResponseMessage(e.getMessage());
			
		}
	    if (e instanceof MethodArgumentNotValidException){
			response.setResponseCode(CollectManageBffResponseCode.RC_PARAMETER_ERROR.getResponseCode());
			response.setResponseMessage(CollectManageBffResponseCode.RC_PARAMETER_ERROR.getResponseMessage());
			
		}else{
			response.setResponseCode(CollectManageBffResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
			if(e.getMessage()!=null){
				response.setResponseMessage(e.getMessage());
			}else{
				response.setResponseMessage(CollectManageBffResponseCode.RC_EXCEPTION_ERROR.getResponseMessage());
			}
		}
		return response;
	}
}
